//
//  PersonalCenterViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/2.
//  Copyright © 2018年 张庆勇. All rights reserved.
#import "PersonalCenterViewController.h"
#import "PresonaModle.h"
#import "PresonalHeadView.h"
#import "PresonaCell.h"
#import "SetViewController.h"
#import "CurrencyAddressViewController.h"
#import "SecurityCenterViewController.h"
#import "IdentityAuthenticationViewController.h"
#import "MyAssetsViewController.h"
#import "OrderListViewController.h"
#import "LoginViewController.h"
#import "FailViewController.h"
#import "CertifiedViewController.h"
#import "LLWebViewController.h"
#import "InvitingFriendsViewController.h"
#import "CheckVersionAlearView.h"
#import "CertifiedViewController.h"
#import "BaseTabBarController.h"
#import "JoinCommunityViewController.h"
#import "HelpMainViewController.h"
#import "InvitationWebViewController.h"
#define headViewHeight RealValue_W(508)
@interface PersonalCenterViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)NSMutableArray * dataAry;
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)PresonalHeadView *tableviewHeadView;
//1是已提交，2是成功，3是失败，4是审核中
@end
@implementation PersonalCenterViewController
- (void)viewWillAppear:(BOOL)animated
{
     [self.navigationController setNavigationBarHidden:YES animated:NO]; //设置隐藏
    [self statusBarStyleIsDark:NO];
}
- (void)viewDidAppear:(BOOL)animated
{
    if ([EXUserManager RealName].integerValue !=2 &&[EXUserManager isLogin]) //没有认证时刻检测认证状态
    {
        [self getUserInfo];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self statusBarStyleIsDark:[ZBLocalized sharedInstance].StatusBarStyle];
    [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏
    [super viewWillDisappear:animated];
}
/*自动退出登陆*/
- (void)exitLogon
{
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [self presentViewController:loginView animated:YES completion:nil];
}
/*设置密码*/
- (void)SetThePassword
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [self presentViewController:loginView animated:YES completion:nil];
}
/*认证提交之后成功*/
- (void)VerificationSusess
{
    [self getUserInfo];
}
/*登陆成功后*/
- (void)LoginSusess
{
    [self getUserInfo];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(exitLogonmessage) name:ExitLogonNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(SetThePassword) name:SetThePasswordNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(VerificationSusess) name:VerificationSusessNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(exitLogonmessage) name:ManualExitLogonNotificationse object:nil];
    [self getData];
    [self getUserInfo];
}
// 接口返回提示未登陆下处理的逻辑
- (void)exitLogonmessage
{
     [self.tableviewHeadView getUserInfo:Localized(@"user_Log_In") lastLoginTime:@"UID: --"];
     self.tableviewHeadView.authenticationLable.hidden = YES;
}
- (void)getUserInfo
{
    WeakSelf
    [HomeViewModel getUserWithDic:@{} url:getUser callBack:^(BOOL isSuccess, id callBack) {
        
        if (!isSuccess) {
            [self axcBasePopUpWarningAlertViewWithMessage:callBack[@"message"] view:kWindow];
        }else
        {
            [weakSelf.tableviewHeadView getUserInfo:[NSString isEmptyString:[EXUserManager personalData].phone]?[EXUserManager personalData].email:[EXUserManager personalData].phone lastLoginTime:[EXUserManager personalData].id];
            
            [weakSelf.tableviewHeadView getRealName:[EXUserManager RealName].integerValue];
        }
    }];  
}
#pragma mark----数据
- (void)getData
{
    NSMutableArray * mutabarray = [[NSMutableArray alloc] init];
    NSMutableArray * firestarray = [[NSMutableArray alloc] init];
    [firestarray addObject:@{@"image":@"icon_me_order",@"title":Localized(@"my_Order_management"),@"controllerClass":[OrderListViewController class]}];
    [firestarray addObject:@{@"image":@"icon_me_wallet",@"title":Localized(@"my_assets"),@"controllerClass":[MyAssetsViewController class]}];
    [firestarray addObject:@{@"image":@"icon_map",@"title":Localized(@"my_Currency_address"),@"controllerClass":[CurrencyAddressViewController class]}];
    NSMutableArray * secondarray = [[NSMutableArray alloc] init];
    [secondarray addObject: @{@"image":@"my_invitation",@"title":Localized(@"my_invitation"),@"controllerClass":[InvitingFriendsViewController class]}];
    [secondarray addObject: @{@"image":@"my_help",@"title":Localized(@"my_help"),@"controllerClass":[HelpMainViewController class]}];
    [secondarray addObject: @{@"image":@"my_joinCommunity",@"title":Localized(@"my_joinCommunity"),@"controllerClass":[JoinCommunityViewController class]}];
    if ([[EXUnit getSite] isEqualToString:@"ZG"])
    {
         [secondarray addObject: @{@"image":@"b_us",@"title":Localized(@"Authentication_us_message"),@"controllerClass":[InvitingFriendsViewController class]}];
    }
    [mutabarray addObject:firestarray];
    [mutabarray addObject:secondarray];
    for (int i=0; i<mutabarray.count; i++)
    {
        NSMutableArray *a=[[NSMutableArray alloc]init];
        for (NSDictionary *dic in mutabarray[i])
        {
            PresonaModle *modle=[[PresonaModle alloc]init];
            modle.title=dic[@"title"];
            modle.image=dic[@"image"];
            modle.controllerClass=dic[@"controllerClass"];
            [a addObject:modle];
        }
         [self.dataAry addObject:a];
    }
    [_tableView reloadData];
    
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - TABBAR_HEIGHT1 -IPhoneTop)];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[PresonaCell class] forCellReuseIdentifier:@"PresonaCell"];
        _tableView.tableHeaderView = self.tableviewHeadView;
        
    }
    return _tableView;
}
- (NSMutableArray *)dataAry
{
    if (!_dataAry) {
        _dataAry = [[NSMutableArray alloc]init];
    }
    return _dataAry;
}
- (PresonalHeadView*)tableviewHeadView{
    WeakSelf
    if (!_tableviewHeadView) {
        
        _tableviewHeadView =[[ PresonalHeadView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, headViewHeight + IPhoneTop)];
        _tableviewHeadView.backgroundColor = MAINBLACKCOLOR;
        if ([EXUserManager isLogin])
        {
           
            [_tableviewHeadView getUserInfo:[NSString isEmptyString:[EXUserManager personalData].phone]?[EXUserManager personalData].email:[EXUserManager personalData].phone lastLoginTime:[EXUserManager personalData].id];
            [_tableviewHeadView getRealName:[EXUserManager RealName].integerValue];
        }else
        {
            [self.tableviewHeadView getUserInfo:Localized(@"user_Log_In") lastLoginTime:@"UID: --"];
             self.tableviewHeadView.authenticationLable.hidden = YES;
        }
       
        _tableviewHeadView.setBlock = ^(UIButton *button) { //设置
            
            SetViewController * setVC = [[SetViewController alloc] init];
            setVC.title = Localized(@"Set");
            [weakSelf.navigationController pushViewController:setVC animated:YES];
        };
        _tableviewHeadView.setSkinBlock = ^(UIButton *button) { //设置皮肤
            
           
            NSString * color =  [[ZBLocalized sharedInstance]AppbBGColor];
            
            if ([NSString isEmptyString:color] ||[color isEqualToString:BLACK_COLOR]) //app风格为默认色
            {
                
                [[ZBLocalized sharedInstance] setAppbBGColor:WHITE_COLOR];
                
            }else if ([color isEqualToString:WHITE_COLOR])//app风格为白色
            {
                [[ZBLocalized sharedInstance] setAppbBGColor:BLACK_COLOR];
            }
            button.selected = !button.selected;
            [weakSelf initRootVC];
        };
        _tableviewHeadView.authenticationBlock = ^(UIButton *button) {
           
            if ([EXUserManager isLogin]) {
                [weakSelf authenticationwithButton:button];
            }else
            {
                [weakSelf exitLogonmessage];
                [weakSelf exitLogon];
            }
            
        };
    };
    return _tableviewHeadView;
}
- (void)authenticationwithButton:(UIButton *)button
{
    
    if (button.tag ==0)
    {
        WeakSelf
        if ([AppDelegate shareAppdelegate].isBecomeActive) {
            if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
                [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                    if(!error){
                        //验证成功，主线程处理UI
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            // 处理耗时操作的代码块...
                            
                            //通知主线程刷新
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                [weakSelf IdentityAuthenticationWithindexPath];
                            });
                            
                        });
                    }else{
                        //验证成功，主线程处理UI
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            // 处理耗时操作的代码块...
                            
                            //通知主线程刷新
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                [EXUserManager removeUserInfo];
                                [weakSelf exitLogon];
                                [weakSelf exitLogonmessage];
                            });
                            
                        });
                        
                    }
                }];
            }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
            {
                //验证手势密码
                [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                    if (result) {
                        
                        [weakSelf IdentityAuthenticationWithindexPath];
                    }else
                    {
                        [EXUserManager removeUserInfo];
                        [weakSelf exitLogon];
                        [weakSelf exitLogonmessage];
                    }
                    
                    
                }];
                
            }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
            {
                [weakSelf IdentityAuthenticationWithindexPath];
            }
        }else
        {
            [weakSelf IdentityAuthenticationWithindexPath];
        }
    }else
    {
        WeakSelf
        if ([AppDelegate shareAppdelegate].isBecomeActive) {
            if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
                [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                    if(!error){
                        //验证成功，主线程处理UI
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            // 处理耗时操作的代码块...
                            
                            //通知主线程刷新
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf pushViewsClassWithindexPathWithButton:button];
                            });
                            
                        });
                    }else{
                        //验证成功，主线程处理UI
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            // 处理耗时操作的代码块...
                            
                            //通知主线程刷新
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [EXUserManager removeUserInfo];
                                [weakSelf exitLogon];
                                [weakSelf exitLogonmessage];
                            });
                            
                        });
                        
                    }
                }];
            }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
            {
                //验证手势密码
                [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                    if (result) {
                        [weakSelf pushViewsClassWithindexPathWithButton:button];
                    }else
                    {
                        [EXUserManager removeUserInfo];
                        [weakSelf exitLogon];
                        [weakSelf exitLogonmessage];
                    }
                    
                    
                }];
                
            }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
            {
                [weakSelf pushViewsClassWithindexPathWithButton:button];
            }
        }else
        {
            [weakSelf pushViewsClassWithindexPathWithButton:button];
        }
    }
}
- (void)pushViewsClassWithindexPathWithButton:(UIButton *)button
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    if (![[EXUnit getSite] isEqualToString:@"BitAladdin"]) {
        if (button.tag ==2)
        {
            if ([EXUserManager RealName].integerValue ==0) { //未认证
                [self popRealNameWithtitle:Localized(@"transaction_authenticated_title") message:Localized(@"my_real_name_message")];
                return;
                
            }else if ([EXUserManager RealName].integerValue ==1 ||[EXUserManager RealName].integerValue ==4)//审核中
            {
                [EXUnit showMessage:Localized(@"C2C_under_review")];
                return;
            }else if ([EXUserManager RealName].integerValue ==3)//认证失败
            {
                [self popRealNameWithtitle:Localized(@"transaction_authenticated_title") message:Localized(@"my_Authentication_failure_message")];
                return;
            }
        }
    }
    NSString * className = _tableviewHeadView.contonts[button.tag][@"controllerClass"];
    Class class = className.class;
    BaseViewViewController *  controllerClass = class.new;
    controllerClass.navigationItem.title = _tableviewHeadView.contonts[button.tag][@"title"];
    [self.navigationController pushViewController:controllerClass animated:YES];
    
    

}
- (void)IdentityAuthenticationWithindexPath
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    switch ([EXUserManager RealName].integerValue) {
            
        case 0: //未认证
        {
            IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
            idACationVC.title = Localized(@"my_identity_authentication");
            [self.navigationController pushViewController:idACationVC animated:YES];
        }
            break;
        case 1: //审核中
        {
            
            IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
            idACationVC.title = Localized(@"my_identity_authentication");
            [self.navigationController pushViewController:idACationVC animated:YES];
            
        }
            break;
        case 2: //已认证
        {
            CertifiedViewController * CertifiedVC  = [[CertifiedViewController alloc] init];
            CertifiedVC.title = Localized(@"my_identity_info");
            [self.navigationController pushViewController:CertifiedVC animated:YES];
        }
            
            break;
        case 3: //认证失败
        {
            FailViewController * failVC = [[FailViewController alloc] init];
            failVC.title = Localized(@"my_Authentication_failure");
            [self.navigationController pushViewController:failVC animated:YES];
        }
            break;
        case 4: //审核中
        {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"C2C_under_review") view:kWindow];
        }
            break;
            
        default:
            break;
    }
}
- (void)popRealNameWithtitle:(NSString *)title message:(NSString *)message
{
    CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                             titleStr:title
                                                                              openUrl:@""
                                                                              confirm:Localized(@"transaction_OK")
                                                                               cancel:Localized(@"transaction_cancel")
                                                                                state:2
                                                                        RechargeBlock:^
                                        {
                                            
                                            IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
                                            idACationVC.title = Localized(@"my_identity_authentication");
                                            [[EXUnit currentViewController].navigationController pushViewController:idACationVC animated:YES];
                                            
                                            
                                        }];
    aleartVC.animationStyle = LXASAnimationTopShake;
    [aleartVC showLXAlertView];
    
}
- (void)initRootVC{
    [AppDelegate shareAppdelegate].window.backgroundColor=MAINBLACKCOLOR;
    BaseTabBarController * tabr = [[BaseTabBarController alloc] init];
    [AppDelegate shareAppdelegate].window.rootViewController = tabr;
    [[AppDelegate shareAppdelegate].window makeKeyAndVisible];
    tabr.selectedIndex = [ZBLocalized sharedInstance].tabNum-1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array=_dataAry[section];
    return array.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return RealValue_W(20);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, RealValue_W(20))];
    view.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PresonaCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"PresonaCell"];
    cell.model=_dataAry[indexPath.section][indexPath.row];;
    cell.rightlable.hidden = YES;
    cell.rightImg.hidden = YES;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

     PresonaModle *si = _dataAry[indexPath.section][indexPath.row];
    if (![si.title isEqualToString:Localized(@"my_help")] &&  ![si.title isEqualToString:Localized(@"my_joinCommunity")]) {
        
        if (![EXUserManager isLogin]) {
            [self exitLogon];
          
            return;
        }
        
        WeakSelf
        if ([AppDelegate shareAppdelegate].isBecomeActive) {
            if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
                [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                    if(!error){
                        //验证成功，主线程处理UI
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            // 处理耗时操作的代码块...
                            
                            //通知主线程刷新
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf pushViewsClassWithindexPath:indexPath];
                            });
                            
                        });
                    }else{
                        //验证成功，主线程处理UI
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            // 处理耗时操作的代码块...
                            
                            //通知主线程刷新
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [EXUserManager removeUserInfo];
                                [weakSelf exitLogon];
                                [weakSelf exitLogonmessage];
                            });
                            
                        });
                        
                    }
                }];
            }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
            {
                //验证手势密码
                [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                    if (result) {
                        [weakSelf pushViewsClassWithindexPath:indexPath];
                    }else
                    {
                        [EXUserManager removeUserInfo];
                        [weakSelf exitLogon];
                        [weakSelf exitLogonmessage];
                    }
                    
                    
                }];
                
            }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
            {
                [weakSelf pushViewsClassWithindexPath:indexPath];
            }
        }else
        {
            [weakSelf pushViewsClassWithindexPath:indexPath];
        }
    }else
    {
        [self pushViewsClassWithindexPath:indexPath];
    }
    
}

- (void)pushViewsClassWithindexPath:(NSIndexPath *)indexPath
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    NSArray * array =  _dataAry[indexPath.section];
    if ([[EXUnit getSite] isEqualToString:@"ZG"]) {
        if (indexPath.section ==1 && indexPath.row == array.count -1)
        {
            QYSource *source = [[QYSource alloc] init];
            source.title = @"ZG.com";
            source.urlString = @"";
            QYSessionViewController *sessionViewController = [[QYSDK sharedSDK] sessionViewController];
            sessionViewController.sessionTitle = @"ZG.com";
            sessionViewController.source = source;
            sessionViewController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:sessionViewController animated:YES];
            return;
        }
    }
     PresonaModle *si = _dataAry[indexPath.section][indexPath.row];
    if (![si.title isEqualToString:Localized(@"my_help")] &&  ![si.title isEqualToString:Localized(@"my_joinCommunity")]) {
 
        if (![EXUserManager isLogin]) {
            [self exitLogon];
            return;
        }
    }
    
        if ([si.title isEqualToString:Localized(@"my_invitation")]) {
            
            if (![[EXUnit getSite] isEqualToString:@"BitAladdin"]  &&![[EXUnit getSite] isEqualToString:@"ZG"]&&![[EXUnit getSite] isEqualToString:@"KCoin"])
            {
                InvitationWebViewController *webV = [InvitationWebViewController new];
                NSArray *array = [HOST_IP componentsSeparatedByString:@"/"]; //从字符A中分隔成2个元素的数组
                NSString * url = [NSString stringWithFormat:@"%@//%@/activity/Superbroker/Invite_recode",array[0],array[2]];
//               NSString * url =  [NSString stringWithFormat:@"http://47.97.206.151:3000/activity/Superbroker/Invite_recode"];
                webV.urlStr =  url;
                webV.isPullRefresh = YES;
                [self.navigationController pushViewController:webV animated:YES];
                return;
            }
        }
    
  
    BaseViewViewController *vc = [[si.controllerClass alloc] init];
    vc.navigationItem.title = si.title;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView) {
        CGFloat offY = scrollView.contentOffset.y;
        if (offY < 0) {
            scrollView.contentOffset = CGPointZero;
        }
    }
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
